<?php
declare(strict_types=1);

namespace App\Controller\v1;

use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\Di\Annotation\Inject;
use App\Controller\AbstractController;
use Hyperf\DbConnection\Db;
use App\Constants\ReturnCode;
use Qbhy\HyperfAuth\Annotation\Auth;
use Qbhy\HyperfAuth\AuthManager;
use App\Helper\Common;
use Throwable;
use App\Service\LoginService;
use App\Service\StatisrecService;
use App\Service\CopyrightService;
use Overtrue\Flysystem\Qiniu\QiniuAdapter;
use App\Middleware\Api\AuthMiddleware;
use App\Service\CommonService;
use App\Service\UserService;
use App\Service\PushService;

#[Controller]
class CommonController extends AbstractController
{
    #[Inject]
    protected LoginService $loginServ;
    #[Inject]
    protected AuthManager $auth;
    #[Inject]
    protected StatisrecService $staServ;
    #[Inject]
    protected CopyrightService $cpyServ;
    #[Inject]
    protected CommonService $comServ;
    #[Inject]
    protected UserService $userServ;
    #[Inject]
    protected PushService $pushServ;
    
    #用户登录
    #[RequestMapping(path: "login", methods: "post")]
    public function login(){
        $type = $this->request->input("type", NULL);
        $device = $this->request->input("device", NULL);
        $version = $this->request->input("version", NULL);
        if(empty($type)){
            return $this->fmt_response(ReturnCode::para_miss,'登录方式错误');
        }
        if(empty($device)){
            return $this->fmt_response(ReturnCode::para_miss,'登录设备错误');
        }
        if(empty($version)){
            return $this->fmt_response(ReturnCode::para_miss,'版本号错误');
        }
        if($type=="ap_code"){
            $code = $this->request->input("code", NULL);
            if(empty($code)){
                return $this->fmt_response(ReturnCode::para_miss,'授权code不能为空');
            }
            $login_data = [
                'type' => $type,
                'code' => $code,
                'device' => $device,
                'version' => $version
            ];
        }elseif($type=="wx_code"){
            $code = $this->request->input("code", NULL);
            if(empty($code)){
                return $this->fmt_response(ReturnCode::para_miss,'授权code不能为空');
            }
            $login_data = [
                'type' => $type,
                'code' => $code,
                'device' => $device,
                'version' => $version
            ];
        }elseif($type=="apple_code"){
            $code = $this->request->input("code", NULL);
            if(empty($code)){
                return $this->fmt_response(ReturnCode::para_miss,'授权code不能为空');
            }
            $login_data = [
                'type' => $type,
                'code' => $code,
                'device' => $device,
                'version' => $version
            ];
        }

        $data = $this->loginServ->doLogin($login_data);
        if($data['status'] !== 1){
            return $this->fmt_response(ReturnCode::para_error,$data['msg']);
        }
        return $this->fmt_response(ReturnCode::deal_succ,'登陆成功',$data['data']);
    }
    #获取系统配置
    #[RequestMapping(path: "confs", methods: "post")]
    public function confs(){
        $key = $this->request->input("key", NULL);
        if(empty($key)){
            return $this->fmt_response(ReturnCode::para_miss,'key错误');
        }
        //省
        if($key=="province"){
            $data = Common::getProvince();
        //市
        }elseif($key=="city"){
            $parent_id = $this->request->input("parent_id", "");
            $data = Common::getCity($parent_id);
        //全部
        }elseif($key=="allcity"){
            $data = Common::getAllCity();
        //其他
        }else{
            $data = Common::getSystemConf($key);
        }
        return $this->fmt_response(ReturnCode::deal_succ,'获取成功',$data);
    }
    #点击统计
    #[RequestMapping(path: "hits", methods: "post")]
    public function hits(){
        $token = $this->request->input('token', NULL);
        if(!empty($token)){
            $is_login = $this->auth->guard('app')->check($token);
            if ($is_login) {
                $payload = $this->auth->guard('app')->getPayload($token);
                $user_id = $payload['uid'];
            }else{
                $user_id = Common::getUserIp();
            }
        }else{
            $user_id = Common::getUserIp();
        }
        $tag = $this->request->input("tag", NULL);
        $device = $this->request->input("device", NULL);
        $id = $this->request->input("id", NULL);
        $data = $this->request->input("data", NULL);
        if(empty($tag)){
            return $this->fmt_response(ReturnCode::para_miss,'统计标签错误');
        }
        if(empty($device)){
            return $this->fmt_response(ReturnCode::para_miss,'统计设备错误');
        }
        if($tag=="msg_hit"){
            $static_params = [
                'device'=>$device,
                'tag'=>$tag,
                'user_id'=>$user_id,
                'id'=>$id,
                'data'=>$data,
                'save_type'=>'normal'
            ];
            $this->pushServ->updateRead($id);
            $res = $this->staServ->doSave($static_params);
        }else{
            $static_params = [
                'device'=>$device,
                'tag'=>$tag,
                'user_id'=>$user_id,
                'id'=>$id,
                'data'=>$data,
                'save_type'=>'norepeat'
            ];
            $res = $this->staServ->doSave($static_params);
        }
        return $this->fmt_response(ReturnCode::deal_succ,'成功');
    }
    #获取七牛配置
    #[RequestMapping(path: "uploadtoken", methods: "post")]
    public function uploadtoken()
    {
        $mod = $this->request->input('mod', NULL);
        if(empty($mod)){
            return $this->fmt_response(ReturnCode::para_miss,'模块错误');
        }
        $accessKey = env('QINIU_ACCESS_KEY');
        $secretKey = env('QINIU_SECRET_KEY');
        $bucket = env('QINIU_BUCKET');
        $domain = env('QINBIU_DOMAIN');
        $adapter = new QiniuAdapter($accessKey, $secretKey, $bucket, $domain);
        $token = $adapter->getUploadToken();
        $return_data = [
            'host' => "http://7img.51sqbby.com/",
            'bucket' => "grabmt",
            'path' => "grabpiao/".$mod."/".date("Ymd")."/",
            'token' => $token
        ];
        return $this->fmt_response(ReturnCode::deal_succ,'成功',$return_data);
    }
    #获取文案
    #[Middleware(AuthMiddleware::class)]
    #[RequestMapping(path: "copyrights", methods: "post")]
    public function copyrights()
    {
        $type = $this->request->input('type', NULL);
        $office_id = $this->request->input('office_id', NULL);
        $user_id = $this->request->getAttribute('user_id');
        $begin_date = $this->request->input('begin_date', NULL);
        $end_date = $this->request->input('end_date', NULL);
        if(empty($type)){
            return $this->fmt_response(ReturnCode::para_miss,'类型错误');
        }
        $params = [
            'office_id'=>$office_id,
            'user_id'=>$user_id,
            'begin_date'=>$begin_date,
            'end_date'=>$end_date,
        ];
        $res = $this->cpyServ->shareCopyright($type,$params);
        return $this->fmt_response(ReturnCode::deal_succ,'成功',$res);
    }
    #保存设备号
    #[Middleware(AuthMiddleware::class)]
    #[RequestMapping(path: "registration", methods: "post")]
    public function registration()
    {
        $device = $this->request->input('device', NULL);
        $platform = $this->request->input('platform', NULL);
        $reg_id = $this->request->input('reg_id', NULL);
        $user_id = $this->request->getAttribute('user_id');
        if(empty($user_id)){
            return $this->fmt_response(ReturnCode::token_miss,'用户未登录');
        }
        if(empty($device)){
            return $this->fmt_response(ReturnCode::para_miss,'设备类型错误');
        }
        if(empty($platform)){
            return $this->fmt_response(ReturnCode::para_miss,'平台类型错误');
        }
        if(empty($reg_id)){
            return $this->fmt_response(ReturnCode::para_miss,'设备号错误');
        }
        $params = [
            'user_id'=>$user_id,
            'device'=>$device,
            'platform'=>$platform,
            'reg_id'=>$reg_id,
        ];
        $res = $this->comServ->regIdSave($params);
        return $this->fmt_response(ReturnCode::deal_succ,'成功',$res);
    }
    #协议
    #[RequestMapping(path: "protocol", methods: "post")]
    public function protocol()
    {
        $res = $this->userServ->protocol();
        return $this->fmt_response(ReturnCode::deal_succ, '成功', $res);
    }
    #悬浮秒表
    #[RequestMapping(path: "watch", methods: "post")]
    public function watch()
    {
        $res = $this->comServ->watchInfo();
        return $this->fmt_response(ReturnCode::deal_succ, '成功', $res);
    }
    #获取系统参数
    #[RequestMapping(path: "sysparam", methods: "post")]
    public function sysparam()
    {
        $aliasname = $this->request->input('aliasname', NULL);
        if(empty($aliasname)){
            return $this->fmt_response(ReturnCode::token_miss,'参数错误');
        }
        $where = [
            ['aliasname', '=', $aliasname]
        ];
        $res = Db::table('system_param')
            ->select(['name','numvalue','bovalue'])
            ->where($where)
            ->first();
        return $this->fmt_response(ReturnCode::deal_succ, '成功', $res);
    }
}